// 商品详情
const api = require('../../../utils/api') // 引入API
const {
  myRequest
} = require('../../../utils/myRequest') // 请求函数
const WxParse = require('../../../libs/wxParse/wxParse.js') // 富文本解析
let goodsList = [
  {actEndTime: '2019-03-10 00:00:00'}
]
Page({
  data: {
    id: '', // 商品id
    infoList: [], // 商品详情列表
    issueList: [], // 问答
    gallery: [], // 轮播
    attribute: [], // 活动
    comment: {}, // 评论
    brand: {}, // 品牌
    specificationList: [], // 规格
    productList: [], // 产品列表
    isConfirm: true, // 弹窗显示隐藏
    isConfirm_select: true,
    clickConfirm_issue: true,
    colorId: '', // 选中颜色id
    sizeId: '', // 选中规格id
    price_number: '1_3',
    productListArr: {},
    goodsTotalCount: 1, // 商品总数量
    totalPrice: '', // 总价
    cartObject: {}, // 存放添加商品到购物车数据
    countDownList: [],
    actEndTimeList: []
  },
  onLoad: function (options) {
    let id = options.id;
    console.log(id);
    myRequest({
      url: api.goodsDetail,
      data: {
        id: id
      },
      success: res => {
        console.log(res);

        let infoList = res.data.data.info;
        let issueList = res.data.data.issue;
        let attribute = res.data.data.attribute;
        let gallery = res.data.data.gallery;
        let comment = res.data.data.comment;
        let brand = res.data.data.brand;
        let specificationList = res.data.data.specificationList;
        let productList = res.data.data.productList;
        this.setData({
          id: id,
          infoList: infoList,
          issueList: issueList,
          attribute: this.processData(res.data.data.attribute),
          gallery: gallery,
          comment: comment,
          brand: brand,
          specificationList: specificationList,
          productList: productList
        })
        this.priceNumber()
        WxParse.wxParse('goods_brief', 'html', infoList.goods_desc, this, 5)
      }
    })
    let endTimeList = [];
    // 将活动的结束时间参数提成一个单独的数组，方便操作
    goodsList.forEach(o => {endTimeList.push(o.actEndTime)})
    this.setData({ actEndTimeList: endTimeList});
    // 执行倒计时函数
    this.countDown();
  },
  // 弹窗点击事件
  // 品牌活动
  clickConfirm() {
    this.setData({
      isConfirm: !this.data.isConfirm
    })
  },
  // 价格，颜色，尺寸弹窗
  clickConfirmSelect() {
    this.setData({
      isConfirm_select: !this.data.isConfirm_select
    })
  },
  // 问答弹窗
  clickConfirmIssue() {
    this.setData({
      clickConfirm_issue: !this.data.clickConfirm_issue
    })
  },
  // 选中颜色
  selectColor(e) {
    let colorId = e.currentTarget.dataset.colorid
    let price_number = this.data.sizeId + '_' + colorId
    this.setData({
      colorId: colorId,
      price_number: price_number
    })

    // 选择下标id，返回对应的goodsId, number, productId
    this.data.productList.forEach((item, index) => {
      if (item.goods_specification_ids == price_number) {
        let cartObject = {
          goodsId: item.goods_id,
          productId: item.id,
          number: item.goods_number
        }
        this.setData({
          cartObject: cartObject
        })
      }
    })
    console.log('选中颜色id', colorId);
    this.priceNumber()
  },
  // 选中规格
  selectSize(e) {
    let sizeId = e.currentTarget.dataset.sizeid
    // 价格和库存切换
    let price_number = sizeId + '_' + this.data.colorId
    this.setData({
      sizeId: sizeId,
      price_number: price_number
    })

    // 选择下标id，返回对应的goodsId, number, productId
    this.data.productList.forEach((item, index) => {
      if (item.goods_specification_ids == price_number) {
        let cartObject = {
          goodsId: item.goods_id,
          productId: item.id,
          number: item.goods_number
        }
        this.setData({
          cartObject: cartObject
        })
      }
    })
    console.log('选中规格id', sizeId);
    this.priceNumber()
  },
  //  价格和库存切换函数
  priceNumber() {
    const {
      productList,
      price_number
    } = this.data;
    productList.forEach((item, index) => {
      if (item.goods_specification_ids == price_number) {
        let productListArr = { // 存放价格和数量
          goods_number: item.goods_number,
          retail_price: item.retail_price
        }
        this.setData({
          productListArr: productListArr
        })
      }
    })
  },
  // 数据处理
  processData(data) {
    let arr = []
    data.forEach(item => {
      let value = item.value.replace('\n', '')
      arr.push({
        ...item,
        value: value
      })
    })
    return arr
  },
  // 购买数量减少函数
  cartDecerase() {
    let [price, num] = [0, 0]
    const {
      goodsTotalCount,
      productListArr
    } = this.data;
    num = goodsTotalCount - 1; // 数量减一
    // 数量小于等于0,不在减少
    if (num <= 0) {
      return;
    }
    price = num * productListArr.retail_price // 计算总价
    this.setData({
      goodsTotalCount: num,
      totalPrice: price
    })
  },
  // 购买数量增加函数
  cartAdd() {
    let [price, num] = [0, 0]
    const {
      goodsTotalCount,
      productListArr
    } = this.data;
    num = goodsTotalCount + 1; // 数量加一
    // 计算总价
    price += num * productListArr.retail_price
    this.setData({
      goodsTotalCount: num,
      totalPrice: price
    })
  },
  // 有produclist选择，打开选择列表
  toOrderDetail() {
    // let { goodsTotalCount, specificationList, infoList, totalPrice,colorId, sizeId, id } = this.data;
    // let detailData = {
    //     goodsTotalCount: goodsTotalCount,
    //     picurlId: colorId,
    //     name: infoList.name,
    //     colorId: colorId,
    //     sizeId: sizeId,
    //     totalPrice: totalPrice,
    //     id: id
    // }
    // detailData = JSON.stringify(detailData) // 需要解析

    // 添加到购物车数据
    if (this.data.goodsTotalCount == 0) {
      wx.showToast({
        title: '请选择购买商品',
        duration: 1500,
      });
      return;
    }
    myRequest({
      url: api.cartAdd,
      data: {
        goodsId: this.data.cartObject.goodsId,
        number: this.data.goodsTotalCount,
        productId: this.data.cartObject.productId
      },
      method: "POST",
      success: res => {
        // 如果库存不足，无法添加到购物车和购买
        if (res.data.errno !== 0) {
          wx.showToast({
            title: '库存不足，请选择其他商品',
            icon: 'none',
            duration: 2500,
          });
        } else {
          // 跳转到购物车列表
          wx.switchTab({
            url: '../../TabBar/cart/cart'
          });
        }
      }
    })
  },
  // 加入购物车
  addCart() {
    const {
      productList
    } = this.data;
    myRequest({
      url: api.cartAdd,
      data: {
        goodsId: this.data.cartObject.goodsId,
        number: this.data.goodsTotalCount,
        productId: this.data.cartObject.productId
      },
      method: "POST",
      success: res => {
        // 如果库存不足，无法添加到购物车和购买
          if (res.data.errno !== 0) {
            wx.showToast({
              title: '库存不足，请选择其他商品',
              icon: 'none',
              duration: 2500,
            });
          } else {
            wx.showToast({
              title: '已成功添加到购物车',
              icon: 'none',
              duration: 2000
            });
          }
      }
    })
  },
  // 收藏
  addcollect() {
    let typeId = 0;
    myRequest({
      url: api.addordelete,
      data: {
        typeId: typeId,
        valueId: this.data.cartObject.goodsId
      },
      method: 'POST',
      success: (res) => {
        wx.showToast({
          title: '已成功添加收藏',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },
  addcollectFun() {
    let typeId = 0;
    myRequest({
      url: api.addordelete,
      data: {
        typeId: typeId,
        valueId: this.data.productList[0].goods_id
      },
      method: 'POST',
      success: (res) => {
        wx.showToast({
          title: '已成功添加收藏',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  // 无produclist选择，直接添加和收藏
  addcollectOder() {
    this.addcollectFun()
  },
  addCartOder() {
    myRequest({
      url: api.cartAdd,
      data: {
        goodsId: this.data.productList[0].goods_id,
        number: this.data.goodsTotalCount,
        productId: this.data.productList[0].id
      },
      method: "post",
      success: res => {
        console.log(res);

        wx.showToast({
          title: '已添加到购物车',
          icon: 'success',
          duration: 2000
        });
      }
    })
  },
  toOrderDetailOder() {
    wx.request({
      url: api.cartAdd,
      data: {
        goodsId: this.data.productList[0].goods_id,
        number: this.data.goodsTotalCount,
        productId: this.data.productList[0].id
      },
      method: "POST",
      success: res => {
        wx.switchTab({
          url: '../../TabBar/cart/cart'
        });
      }
    })
  },
  timeFormat(param){//小于10的格式化函数
    return param < 10 ? '0' + param : param; 
  },
  countDown(){//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = new Date(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0){
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      }else{//活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr.push(obj);
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ countDownList: countDownArr})
    setTimeout(this.countDown,1000);
  }
})